package com.itelite.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itelite.common.info.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/5/13-15:34
 **/
@Component
@Slf4j
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Autowired
    private ObjectMapper objectMapper;
    //登录成功后调用
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
//        logger.info("登录失败"+exception.getMessage());
        if(exception.getMessage().equals("Token过期")){
            //需要调刷新的接口
            response.setHeader("EXPIRE_TOKEN","1111");
        }
        //根据配置信息来判断登录失败是进行跳转还是返回json信息
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(Result.failure(exception.getMessage())));
    }
}
